import Toast from '@vant/weapp/toast/toast';
const myRequest = require('../../utils/request.js'); // 导入整个模块
const app = getApp()
import {
  createStoreBindings
} from 'mobx-miniprogram-bindings'

import {
  store
} from '../../store/strategy/index'
import {
  writestore
} from '../../store/write/index'
Page({
  data: {
    formats: {},
    readOnly: false,
    placeholder: '开始输入...',
    keyboardHeight: 0,
    isIOS: false,
    title: '',
    content: '',
    isfocus: false,
    bottomInset: 0,
    bgimg: '', //封面
    updatestrategy: {},
    navBarHeight: 0,
    upheight: 0,
  },


  onEditorReady() {
    // onEditorReady(description) {
      console.log(111);
    const that = this
    that.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
      if (!res) return
      if(that.data.content){
        that.editorCtx.setContents({
          html: that.data.updatestrategy.content,
          success: function (res) {
            console.log("渲染成功")
          },
          fail: function (err) {
            console.log("渲染失败")
          }
        })
      }
      
    }).exec()
  },

  onStatusChange(e) {
    const formats = e.detail
    this.setData({
      formats
    })
  },
  bindcontentInput(e) {
    this.setData({
      content: e.detail.value
    })
  },

  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)

  },

  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },
  onLoad() {
    

    const systemInfo = wx.getWindowInfo();
    const bottomInset = Math.abs(systemInfo.safeArea.bottom - systemInfo.windowHeight);
    const platform = wx.getWindowInfo().platform
    const isIOS = platform === 'ios'
    // 创建 store 的绑定
    this.strategyBindings = createStoreBindings(this, {
      store,
      fields: ['strategy'],
      actions: ['updatestrategy']
    });
    // 创建 writestore 的绑定
    this.writeStrategyBindings = createStoreBindings(this, {
      store: writestore,
      fields: ['writestrategy'],
      actions: ['updatewritestrategy']
    });

    this.setData({
      updatestrategy: store.strategy,
    })
    this.setData({
      isIOS,
      bottomInset,
      navBarHeight: systemInfo.statusBarHeight + 40
    })

    const that = this
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      console.log(res);
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)

    })
  },
  onShow() {
    this.setData({
      updatestrategy: store.strategy,
    })
    if (this.data.updatestrategy.id) {
      this.setData({
        title: this.data.updatestrategy.title,
        bgimg: this.data.updatestrategy.img,
        content:this.data.updatestrategy.content
      })
      if(this.editorCtx){
        this.editorCtx.setContents({
          html: this.data.content,
          success: function (res) {
            console.log("渲染成功")
          },
          fail: function (err) {
            console.log("渲染失败")
          }
        })
      }
      
    }

  },
  onHide() {
    this.setData({
      title: '',
      bgimg: '',
      content: ''
    })  

    this.editorCtx.setContents({
      html: '',
      success: function (res) {
        console.log("渲染成功")
      },
      fail: function (err) {
        console.log("渲染失败")
      }
    })
    
  },

  //封面上传
  uploadimg(event) {
    const that = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      success: function (res) {
        wx.uploadFile({
          url: app.globalData.baseAPI + '/upload',
          filePath: res.tempFiles[0].tempFilePath,
          name: 'file',
          header: {
            'content-type': 'application/json',
            'authorization': wx.getStorageSync('token')
          },

          success(uploadres) {
            console.log(JSON.parse(uploadres.data).imagePath);
            that.setData({
              bgimg: JSON.parse(uploadres.data).imagePath
            })
          },
          fail(res) {
            console.log('upload fail');
          }
        })

      }
    })
  },
  // 获得焦点
  editorfocus(e) {
    this.setData({
      isfocus: true
    })
  },

  // 失去焦点
  getblur() {
    this.setData({
      isfocus: false
    })
  },
  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const {
      windowHeight,
      platform
    } = wx.getWindowInfo()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight

    this.setData({
      editorHeight,
      keyboardHeight: keyboardHeight,
      upheight: keyboardHeight + this.data.bottomInset
    })

  },
  calNavigationBarAndStatusBar() {
    const platform = wx.getDeviceInfo().platform
    const statusBarHeight = wx.getWindowInfo().statusBarHeight
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },

  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    })
  },
  // 标题输入
  bindKeyInput: function (e) {
    if (e.detail.cursor > 30) {
      this.setData({
        title: this.data.title
      })
      Toast('标题不能超过30个字！')
      return
    }
    this.setData({
      title: e.detail.value
    })
  },

  // 发布游记
  nextstep() {
    let that = this
    this.editorCtx.getContents({
      success: (res) => {
        that.setData({
          content: res.html
        })
        if (that.data.content && that.data.title && that.data.bgimg && that.data.content != '<p><br></p>') {
         if(that.data.updatestrategy.id){
          writestore.updatewritestrategy({...that.data.updatestrategy,
            content: that.data.content,
            title: that.data.title,
            bgimg: that.data.bgimg
          })
         }else{
          writestore.updatewritestrategy({
            content: that.data.content,
            title: that.data.title,
            bgimg: that.data.bgimg
          })
         }
         
          wx.navigateTo({
            url: '/pages/secondwrite/index',
          })

        } else {
          Toast('请先补充完信息再进行下一步哦！')
          return
        }
      }
    })



  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  insertImage() {
    const that = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      success: function (res) {
        console.log(res.tempFiles[0].tempFilePath)
        console.log(res.tempFiles[0].size)
        wx.uploadFile({
          url: app.globalData.baseAPI + '/upload',
          filePath: res.tempFiles[0].tempFilePath,
          name: 'file',
          header: {
            'content-type': 'application/json',
            'authorization': wx.getStorageSync('token')
          },

          success(uploadres) {
            console.log(JSON.parse(uploadres.data).imagePath);
            that.editorCtx.insertImage({
              src: JSON.parse(uploadres.data).imagePath,

              width: '80%',
              success: function () {
                console.log('insert image success')
              }
            })
          },
          fail(res) {
            console.log('upload fail');
          }
        })

      }
    })
  },

})